"""
公告配置
"""
import logging
from datetime import datetime

from django.db.models import Q

from biz.core.thanos.models import AnnounceMent
from biz.exceptions import ERROR_DATA_NOT_EXISTS
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException

_LOGGER = logging.getLogger(__name__)


def list_announcement(pro_id, page_no, page_size, is_flash=None, pkg=None, chn=None):
    assert page_no > 0
    assert page_size > 0
    query = AnnounceMent.objects.filter(pro_id=pro_id).all()
    local_time = datetime.now()
    if is_flash is not None:
        if is_flash:
            query = query.filter(start_at__lte=local_time, end_at__gte=local_time)
        else:
            query = query.filter(Q(start_at__gte=local_time) | Q(end_at__lte=local_time))
    if pkg:
        query = query.filter(Q(pkg=pkg) | Q(pkg='all'))
    if chn:
        query = query.filter(Q(chn__icontains=chn) | Q(chn='all'))
    return query.count(), [e.to_dict() for e in paginate(query.order_by('-created_at'), page_no, page_size)]


def add_announcement(pro_id, start_at, end_at, pkg, chn, system, title, context):
    data = AnnounceMent.objects.create(start_at=start_at, end_at=end_at, pkg=pkg, chn=chn, system=system,
                                       title=title, context=context, pro_id=pro_id)
    return data.to_dict()


def get_announcement(data_id):
    data = _get_data(data_id)
    return data.to_dict()


def update_announcement(data_id, start_at, end_at, pkg, chn, system, title, context):
    data = _get_data(data_id)
    data.start_at = start_at
    data.end_at = end_at
    data.pkg = pkg
    data.chn = chn
    data.system = system
    data.title = title
    data.context = context
    data.save()
    return data.to_dict()


def delete_announcement(data_id):
    assert data_id
    data = _get_data(data_id)
    data.delete()


def _get_data(data_id):
    assert data_id > 0
    data = AnnounceMent.objects.filter(pk=data_id).first()
    if not data:
        raise BizException(ERROR_DATA_NOT_EXISTS)
    return data
